import net from "net";

export const send = async (json, ip, port) => {
    console.log("sendData... waiting,json->", json);
    return new Promise((resolve, reject) => {
        let client = new net.Socket(); //后期改缓存连接
        client.connect({
            host: ip,
            port: port,
        });

        //客户端与服务器建立连接触发
        client.on("connect", () => {
            client.write(JSON.stringify(json));
        });

        //客户端接收数据触发
        client.on("data", (data) => {
            client.end();
            resolve(safeJsonParse(data.toString()));
        });

        client.on("error", (error) => {
            reject(error);
        });
    });
}

export const safeJsonParse = (data) => {
    try {
        return JSON.parse(data);
    } catch (err) {
        console.log("data :>> ", data);
        return null;
    }
}

